/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - resource
// Copyright( c) 2014.  All Rights Reserved
//
// File:		AERenderableTexture.cpp
// Author:		Gianluca Belardelli
// Date:		11/12/2014
//
/////////////////////////////////////////////////////////////////////////
#include <AEEngine.h>

AERenderableTexture::AERenderableTexture( AEResourceManager *lpParentManager, AERenderableTextureConfig &rtConfig, const char *lpResourceName ) : AETexture( lpParentManager )
{
	m_rtConfig = rtConfig;

	m_sSizeX = m_rtConfig.nWidth;
	m_sSizeY = m_rtConfig.nHeight;
	m_cTextureFormat = m_rtConfig.m_eFormat;
	m_bIsVertexTexture = m_rtConfig.bIsUsableAsVertexTexture;

#if defined(AE_OPENGL) || defined(AE_OPENGLES2) || defined(AEOPENGLES3)
	m_uiGLTargetHandle = GL_INVALID_VALUE;
#endif

}

AERenderableTexture::~AERenderableTexture( void )
{
}

const AERenderableTextureConfig *AERenderableTexture::GetConfig( void ) const
{
	return &m_rtConfig;
}

const AERenderableTextureConfig *AERenderableTexture::GetConfig( void )
{
	return &m_rtConfig;
}

AEBOOL32 AERenderableTexture::IsRenderable( void ) const
{
	return 1;
}

AEBOOL32 AERenderableTexture::Unload( void )
{
	return 0;
}

#if defined(AE_OPENGL) || defined(AE_OPENGLES2) || defined(AEOPENGLES3)

AEBOOL32 AERenderableTexture::Reload( void )
{
	if( m_uiGLTargetHandle != GL_INVALID_VALUE )
		return 0;

	if( m_rtConfig.bRenderTargetOnly )
	{
		glGenTextures( 1, (GLuint *)&m_uiGLTargetHandle );
		if( m_uiGLTargetHandle == GL_INVALID_VALUE )
			return 0;

		glBindTexture( GL_TEXTURE_2D, m_uiGLTargetHandle );
 
		glTexImage2D( GL_TEXTURE_2D, 0,GL_RGB, m_sSizeX, m_sSizeY, 0,GL_RGB, GL_UNSIGNED_BYTE, 0L );
 
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

		return 1;
	}
	else if( m_rtConfig.bIsDepthStencilTarget )
	{
		glGenRenderbuffers(1, (GLuint *)&m_uiGLTargetHandle );
		if( m_uiGLTargetHandle == GL_INVALID_VALUE )
			return 0;

		glBindRenderbuffer( GL_RENDERBUFFER, m_uiGLTargetHandle );
		glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_sSizeX, m_sSizeY );
		glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_uiGLTargetHandle );

		return 1;
	}
	else if( m_rtConfig.bIsUsableAsVertexTexture )
	{
		return 0;
	}

	return 0;
}

AEUINT32 AERenderableTexture::GetRenderTarget( void ) const
{
	return m_uiGLTargetHandle;
}

#else

AEBOOL32 AERenderableTexture::Reload( void )
{
}

#endif
